package com.adk.backend.service.impl;

import com.adk.backend.common.PageResult;
import com.adk.backend.entity.LxEmployeeList;
import com.adk.backend.mapper.EmployeeListMapper;
import com.adk.backend.service.EmployeeListService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 员工列表服务实现类
 */
@Slf4j
@Service
public class EmployeeListServiceImpl extends ServiceImpl<EmployeeListMapper, LxEmployeeList> implements EmployeeListService {
    
    @Autowired
    private EmployeeListMapper employeeListMapper;
    
    @Override
    public PageResult<LxEmployeeList> getEmployeeList(Map<String, Object> params) {
        Integer pageNum = (Integer) params.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) params.getOrDefault("pageSize", 20);
        
        QueryWrapper<LxEmployeeList> wrapper = new QueryWrapper<>();
        
        // 按部门ID筛选
        if (params.get("deptId") != null) {
            wrapper.and(w -> w.eq("dept_id", params.get("deptId"))
                    .or().eq("dept2_id", params.get("deptId"))
                    .or().eq("dept3_id", params.get("deptId"))
                    .or().eq("dept4_id", params.get("deptId")));
        }
        
        // 按员工姓名模糊查询
        if (params.get("empName") != null && !params.get("empName").toString().isEmpty()) {
            wrapper.like("emp_name", params.get("empName"));
        }
        
        // 按员工编号查询
        if (params.get("empNo") != null && !params.get("empNo").toString().isEmpty()) {
            wrapper.eq("emp_no", params.get("empNo"));
        }
        
        wrapper.orderByDesc("id");
        
        Page<LxEmployeeList> page = new Page<>(pageNum, pageSize);
        Page<LxEmployeeList> result = employeeListMapper.selectPage(page, wrapper);
        
        PageResult<LxEmployeeList> pageResult = new PageResult<>();
        pageResult.setList(result.getRecords());
        pageResult.setTotal(result.getTotal());
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotalPages((int) result.getPages());
        
        return pageResult;
    }
    
    @Override
    public LxEmployeeList getEmployeeById(Long id) {
        return employeeListMapper.selectById(id);
    }
    
    @Override
    public LxEmployeeList getEmployeeByEmpNo(String empNo) {
        QueryWrapper<LxEmployeeList> wrapper = new QueryWrapper<>();
        wrapper.eq("emp_no", empNo);
        return employeeListMapper.selectOne(wrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public LxEmployeeList createEmployee(LxEmployeeList employee) {
        // 处理日期字段
        processDateFields(employee);
        employeeListMapper.insert(employee);
        return employee;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEmployee(LxEmployeeList employee) {
        // 处理日期字段
        processDateFields(employee);
        return employeeListMapper.updateById(employee) > 0;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEmployee(Long id) {
        return employeeListMapper.deleteById(id) > 0;
    }
    
    @Override
    public List<LxEmployeeList> getAllEmployeeList(Integer deptId) {
        QueryWrapper<LxEmployeeList> wrapper = new QueryWrapper<>();
        
        if (deptId != null) {
            wrapper.and(w -> w.eq("dept_id", deptId)
                    .or().eq("dept2_id", deptId)
                    .or().eq("dept3_id", deptId)
                    .or().eq("dept4_id", deptId));
        }
        
        wrapper.orderByDesc("id");
        
        return employeeListMapper.selectList(wrapper);
    }
    
    @Override
    public List<LxEmployeeList> getEmployeeListByDeptId(Integer deptId) {
        QueryWrapper<LxEmployeeList> wrapper = new QueryWrapper<>();
        wrapper.and(w -> w.eq("dept_id", deptId)
                .or().eq("dept2_id", deptId)
                .or().eq("dept3_id", deptId)
                .or().eq("dept4_id", deptId));
        wrapper.orderByDesc("id");
        return employeeListMapper.selectList(wrapper);
    }
    
    /**
     * 处理日期字段，将字符串日期转换为时间戳
     */
    private void processDateFields(LxEmployeeList employee) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        
        try {
            // 处理入职日期
            if (employee.getJoinDate() != null && !employee.getJoinDate().isEmpty() && employee.getJoinDateInt() == null) {
                Date date = sdf.parse(employee.getJoinDate());
                employee.setJoinDateInt((int) (date.getTime() / 1000));
            }
            
            // 处理合同到期日期
            if (employee.getContactEndDate() != null && !employee.getContactEndDate().isEmpty() && employee.getContactEndDateInt() == null) {
                Date date = sdf.parse(employee.getContactEndDate());
                employee.setContactEndDateInt((int) (date.getTime() / 1000));
            }
            
            // 处理申请离职日期
            if (employee.getReqLeaveDate() != null && !employee.getReqLeaveDate().isEmpty() && employee.getReqLeaveDateInt() == null) {
                Date date = sdf.parse(employee.getReqLeaveDate());
                employee.setReqLeaveDateInt((int) (date.getTime() / 1000));
            }
            
            // 处理确认离职日期
            if (employee.getConfirmLeaveDate() != null && !employee.getConfirmLeaveDate().isEmpty() && employee.getConfirmLeaveDateInt() == null) {
                Date date = sdf.parse(employee.getConfirmLeaveDate());
                employee.setConfirmLeaveDateInt((int) (date.getTime() / 1000));
            }
            
            // 处理离职日期
            if (employee.getLeaveDate() != null && !employee.getLeaveDate().isEmpty() && employee.getLeaveDateInt() == null) {
                Date date = sdf.parse(employee.getLeaveDate());
                employee.setLeaveDateInt((int) (date.getTime() / 1000));
            }
        } catch (Exception e) {
            log.error("日期解析失败", e);
        }
    }
}

